//
// Created by lau on 2019-10-17.
//

#include <utils/logutils.h>
#include "render.h"
#include "program.h"

namespace VideoEffect {

    Render::Render() {
        glGenBuffers(1, &VAO);
        glBindBuffer(GL_ARRAY_BUFFER, VAO);
        glBufferData(GL_ARRAY_BUFFER, sizeof(VECTICES), VECTICES, GL_STATIC_DRAW);

        glGenBuffers(1, &EBO);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(INDEX), INDEX, GL_STATIC_DRAW);

        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    }

    Render::~Render() {
        if (EBO != 0) {
            glDeleteBuffers(1, &EBO);
            EBO = 0;
        }

        if (VAO != 0) {
            glDeleteBuffers(1, &VAO);
            VAO = 0;
        }
    }

    void Render::draw(Program *program) {
        glBindBuffer(GL_ARRAY_BUFFER, VAO);
        program->setVertexAttribPointer("aPosition", 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (void *) 0);
        program->setVertexAttribPointer("aTextureCoord", 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (void *) (2 * sizeof(GLfloat)));
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void *) 0);
        program->disableVertexAttrib("aPosition");
        program->disableVertexAttrib("aTextureCoord");
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    }

}